/**
 * 请求工具
 */
var ApiUtil = (function () {
    var ACCESS_TOKEN_KEY = "sop_admin_access_token";
    var USER_INFO_KEY = "dian_user_info";

    // 接口URL,更改此处即可
    var url = SopConfig.url();
    var URI_CHAR = '/';
    var params = {};

    (function () {
        var aPairs, aTmp;
        var queryString = window.location.search.toString();
        queryString = queryString.substring(1, queryString.length); //remove   "?"
        aPairs = queryString.split("&");
        for (var i = 0; i < aPairs.length; i++) {
            aTmp = aPairs[i].split("=");
            params[aTmp[0]] = decodeURIComponent(aTmp[1]);
        }
    })();

    function formatUri(uri) {
        if (uri.substring(0, 1) !== URI_CHAR) {
            uri = URI_CHAR + uri;
        }
        if (uri.substring(uri.length - 1) !== URI_CHAR) {
            //uri = uri + URI_CHAR;
        }
        return uri;
    }

    function getAccessToken() {
        return localStorage.getItem(ACCESS_TOKEN_KEY) || '';
    }

    function ajax(uri, params,type, successCallback,errorCallback){
        uri = url+formatUri(uri)
        $.ajax({
            type : type,//向后台请求的方式，有post，get两种方法
            url : uri,//url填写的是请求的路径
            cache : false,//缓存是否打开
            data : $.isEmptyObject(params)?null:JSON.stringify(params),
            contentType : 'application/json',//添加这句话
            dataType : "json",
            success : function(resp) {//请求的返回成功的方法
                var code = resp.code
                if (code === -100 || code === 401 || code === 21) { // 未登录
                    ApiUtil.logout();
                    return
                }
                if (code === 0) { // 成功
                    successCallback(resp)
                } else {
                    if(errorCallback){
                        errorCallback(resp);
                    }else{
                        layer.msg(resp.msg,{icon:5,shift:6})
                    }
                }
            },
            error : function(XMLHttpRequest, textStatus, errorThrown) {//请求的失败的返回的方法
                if(errorCallback){
                    errorCallback(resp);
                }else{
                    common.util.error('系统错误',{icon:5,shift:6})
                }
            }
        });
    }

    return {
        post: function (uri, params, successCallback,errorCallback) {
            ajax(uri,params,'post',successCallback,errorCallback);
        },
        get: function (uri, params, successCallback,errorCallback) {
            ajax(uri,params,'get',successCallback,errorCallback);
        }
        , setAccessToken:function (accessToken) {
            localStorage.setItem(ACCESS_TOKEN_KEY,accessToken);
        }
        , getAccessToken: function () {
            return getAccessToken();
        }
        , setUserInfo:function (userInfo) {
            localStorage.setItem(USER_INFO_KEY,userInfo);
        }
        , getUserInfo: function () {
            return JSON.parse(localStorage.getItem(USER_INFO_KEY)) || '';
        }
        , logout2: function () {
            localStorage.removeItem(ACCESS_TOKEN_KEY);
            top.location.href = '../login/login.html';
        }
        , logout: function () {
            layer.msg('请登陆!', {
                icon: 2,
                time: 2000 //2秒关闭（如果不配置，默认是3秒）
            }, function(){
                ApiUtil.logout2()
            });
        }
        , getUrl: function () {
            return url;
        }
        , createUrl: function (uri, params) {
            if (!uri) {
                throw new Error('uri不能为空');
            }
            return url + formatUri(uri) + (params ? '?data=' + encodeURIComponent(JSON.stringify(params)) : '');
        }
        , getParam: function (paramName) {
            return params[paramName];
        }
    }
})();
